package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IAdminRoleService;
import com.ee.chat.admin.service.IIndexService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.MenuTree;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.AdminMenuMapper;
import com.ee.chat.common.dao.AdminRoleMapper;
import com.ee.chat.common.entity.AdminRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminRoleServiceImpl implements IAdminRoleService {
    @Resource
    AdminRoleMapper adminRoleMapper;
    @Resource
    AdminMenuMapper adminMenuMapper;
    @Resource
    IIndexService indexService;
    @Resource
    IOperationService operationService;

    @Override
    public List<Integer> getRoleMenuPermissionIds(Integer roleId) {
        if(roleId == null){
            return new ArrayList<>();
        }

        AdminRole adminRole = adminRoleMapper.selectById(roleId);
        if(adminRole.getSystem() == 1){ //系统内置超级管理员角色，拥有所有权限
            return adminMenuMapper.getMenuPermissionIds();
        }else{
            return adminRoleMapper.getRoleMenuPermissionIds(roleId);
        }
    }

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Page<AdminRole> p = new Page<>(page, limit);
        IPage<AdminRole> ipage =  adminRoleMapper.getAdminRoles(p);

        data.put("roles", ipage.getRecords());
        data.put("total", ipage.getTotal());

        operationService.addOperationLog(request, "获取角色数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional
    public Result del(HttpServletRequest request, List<Integer> ids) throws Exception {
        for(Integer id : ids){
            AdminRole role = adminRoleMapper.selectById(id);
            if(role.getSystem() == 1){
                return Result.returnFailure("超级管理员为系统内置角色，不能删除");
            }
        }

        adminRoleMapper.deleteBatchIds(ids);

        operationService.addOperationLog(request, "删除角色，ids："+ids);

        return Result.returnSuccess(null);
    }

    @Override
    public Result toEdit(HttpServletRequest request, Integer id) throws Exception {
        Map<String, Object> data = new HashMap<>();

        List<MenuTree> trees = indexService.getMenuPermission();
        data.put("trees", trees);
        AdminRole role = adminRoleMapper.selectById(id);
        data.put("role", role);
        List<Integer> permissionIds = getRoleMenuPermissionIds(id);
        data.put("permissionIds", permissionIds);

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional
    public Result edit(HttpServletRequest request, AdminRole role, List<Integer> permissionIds) throws Exception {
        AdminRole temp = adminRoleMapper.selectById(role.getId());
        if(temp.getSystem() == 1){
            return Result.returnFailure("内置超级管理员角色，不能更改");
        }
        if(permissionIds == null || permissionIds.size() <= 0){
            return Result.returnFailure("请至少选择一个权限");
        }

        if(role.getStatus() == null){
            role.setStatus(1);
        }
        adminRoleMapper.updateById(role);

        adminRoleMapper.delRolePermissionByRoleId(role.getId());
        List<Map<String, Object>> rolePermissions = new ArrayList<>();
        for(Integer id : permissionIds){
            Map<String, Object> rolePermission = new HashMap<>();
            rolePermission.put("roleId", role.getId());
            rolePermission.put("menuId", id);
            rolePermissions.add(rolePermission);
        }
        adminRoleMapper.batchAddRolePermission(rolePermissions);

        operationService.addOperationLog(request, "编辑角色，id："+role.getId());

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional
    public Result save(HttpServletRequest request, AdminRole role, List<Integer> permissionIds) throws Exception {
        QueryWrapper<AdminRole> wrapper = new QueryWrapper<>();
        wrapper.eq("name", role.getName());
        AdminRole adminRole = adminRoleMapper.selectOne(wrapper);
        if(adminRole != null){
            return Result.returnFailure("该角色名称已被占用，请更换角色名称");
        }

        if(permissionIds.size() <= 0){
            return Result.returnFailure("请至少选择一个权限");
        }

        adminRoleMapper.insert(role);

        List<Map<String, Object>> rolePermissions = new ArrayList<>();
        for(Integer id : permissionIds){
            Map<String, Object> rolePermission = new HashMap<>();
            rolePermission.put("roleId", role.getId());
            rolePermission.put("menuId", id);
            rolePermissions.add(rolePermission);
        }
        adminRoleMapper.batchAddRolePermission(rolePermissions);

        operationService.addOperationLog(request, "新增角色，id："+role.getId());

        return Result.returnSuccess(null);
    }

    @Override
    public Result changeStatus(HttpServletRequest request, Integer id) throws Exception {
        AdminRole adminRole = adminRoleMapper.selectById(id);
        if(adminRole.getSystem() == 1){
            return Result.returnFailure("系统内置管理员角色不能更改状态");
        }

        if(adminRole.getStatus() == 0){
            adminRole.setStatus(1);
        }else{
            adminRole.setStatus(0);
        }
        adminRoleMapper.updateById(adminRole);

        operationService.addOperationLog(request, "变更角色状态，id："+id);

        return Result.returnSuccess(null);
    }
}
